const { text, group, log, select, isCancel, cancel } = require("@clack/prompts");
const path = require("path");
const fs = require("fs-extra");
const yaml = require("yaml");
const { getI18nTranslates } = require("../utils");
const { isNil, omitBy } = require("lodash");

const DefaultSettings = {
  exportDir: "./",
  fileNameType: "date",
  exportFileName: "YYYYMMDDHHmm",
  languageDir: "./src/locales",
  fileType: "xlsx",
  defaultLanguage: "zh",
};

const SettingTips = {
  exportDir:
    "# 导出目录\n# 翻译文件的导出目录\n# 默认为当前项目根目录，非当前目录需要设置为绝对路径\n# 例如：C:\\Users\\admin\\Desktop",
  fileNameType:
    "# 导出文件名类型\n# 导出的文件名类型，默认为 date\n# 可选值为 date | fixed\n# - date  日期格式文件，文件名格式默认为: YYYYMMDD HHmm\n# - fixed 固定格式文件，文件名格式为：translate",
  exportFileName:
    "# 导出文件名\n# 导出的文件名，默认为日期格式\n# 当文件名为日期格式时参考：https://day.js.org/docs/zh-CN/display/format\n# 请勿包含特殊字符，否则可能会导致文件无法正常导出",
  languageDir: "# 语言目录\n# 项目中i18n配置文件的目录\n# 默认为 ./src/locales",
  fileType: "# 导出文件类型\n# 默认为xlsx，可选值为 csv、xlsx",
  defaultLanguage: "# 默认语言\n# 项目中默认的语言，在导出时默认语言会作为第一列\n# 默认为 zh，即包含zh的语言",
};

const DefaultConfigFile = `
${SettingTips.exportDir}
exportDir: ${DefaultSettings.exportDir}

${SettingTips.fileNameType}
fileNameType: ${DefaultSettings.fileNameType}

${SettingTips.exportFileName}
exportFileName: ${DefaultSettings.exportFileName}

${SettingTips.languageDir}
languageDir: ${DefaultSettings.languageDir}

${SettingTips.fileType}
fileType: ${DefaultSettings.fileType}

${SettingTips.defaultLanguage}
defaultLanguage: ${DefaultSettings.defaultLanguage}
`;

async function getSettings() {
  const file = path.join(process.cwd(), "./i18n.yaml");
  const str = (await fs.readFile(file).catch(() => "")).toString("utf8");
  const config = { ...DefaultSettings, ...yaml.parse(str) };

  config.exportDir = path.isAbsolute(config.exportDir) ? config.exportDir : path.join(process.cwd(), config.exportDir);
  config.languageDir = path.isAbsolute(config.languageDir)
    ? config.languageDir
    : path.join(process.cwd(), config.languageDir);

  const { languages } = await getI18nTranslates(config.languageDir);

  config.defaultLanguage = languages.find((item) => item.includes("zh")) || languages[0];

  return config;
}

async function main() {
  const filePath = path.join(process.cwd(), "./i18n.yaml");
  const origin = (await fs.readFile(filePath).catch(() => "")).toString("utf8") || DefaultConfigFile;
  const document = yaml.parseDocument(origin);
  const action = await select({
    message: "请选择操作类型",
    options: [
      { value: "create", label: "创建i18n设置文件" },
      { value: "update", label: "更新i18n设置文件" },
    ],
  });

  if (isCancel(action)) {
    cancel("操作取消");
    process.exit(0);
  }

  if (action === "create") {
    await fs.writeFile(filePath, document.toString());
    log.success("已创建i18n设置文件。");
    return;
  }

  const settings = await group({
    exportDir: () =>
      text({
        message: SettingTips.exportDir,
        placeholder: DefaultSettings.exportDir,
      }),
    fileNameType: () =>
      select({
        message: SettingTips.fileNameType,
        options: [
          { value: "date", label: "日期格式" },
          { value: "fixed", label: "固定格式" },
        ],
      }),
    exportFileName: ({ results }) =>
      text({
        message: SettingTips.exportFileName,
        placeholder: results.fileNameType === "date" ? DefaultSettings.exportFileName : "",
        validate: (value) => results.fileNameType === "fixed" && !value && "请输入文件名",
      }),
    languageDir: () =>
      text({
        message: SettingTips.languageDir,
        placeholder: DefaultSettings.languageDir,
      }),
    fileType: () =>
      select({
        message: SettingTips.fileType,
        defaultValue: DefaultSettings.fileType,
        options: [
          { value: "xlsx", label: "xlsx格式" },
          { value: "csv", label: "csv格式" },
        ],
      }),
    defaultLanguage: async ({ results }) => {
      const { languages } = await getI18nTranslates(results.languageDir || DefaultSettings.languageDir);

      if (!languages.length) languages.push("zh");

      return select({
        message: SettingTips.defaultLanguage,
        defaultValue: languages.find((item) => item.includes("zh")) || languages[0],
        options: languages.map((value) => ({ value, label: value })),
      });
    },
  });

  if (isCancel(settings)) {
    cancel("操作取消");
    process.exit(0);
  }

  const merged = { ...DefaultSettings, ...omitBy(settings, isNil) };

  for (const [key, value] of Object.entries(merged)) {
    document.setIn([key], value);
  }
  await fs.writeFile(filePath, document.toString());
  log.success("i18n设置文件已更新");
}

module.exports = { main, getSettings };
